package com.qf.business.auth.controller;

import com.ken.event.action.apply.producer.EventTemplate;
import com.qf.commons.base.result.R;
import com.qf.commons.base.result.Rs;
import com.qf.data.notify.entity.Email;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotBlank;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * author Ken
 * create_time 2022/11/16
 */
@RestController
@RequestMapping("/code")
@Slf4j
@Validated
public class CodeController {

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 发送验证码
     * @param email
     * @return
     */
    @RequestMapping("/send")
    public R sendCode(@NotBlank(message = "邮箱地址不能为空！") String email) {
        log.debug("[send mail code] 发送验证码到邮箱 - {}", email);

        //生成验证码
        String code = getRandomCode();
        redisTemplate.opsForValue().set(email, code, 5, TimeUnit.MINUTES);

        Email emailObject = new Email()
                .setSubject("千锋在线教育平台官方邮件")
                .setSendTime(new Date())
                .addTo(email).setContent("登录验证码：<a style='font-size: 20px; font-weight: 900; color: red;'>" + code + "</a>，如果不是您本人操作，请报警！");
        EventTemplate.sendQuickly("send_email", emailObject);

        //调用邮件API
        return Rs.create();
    }

    /**
     * 生成一个验证码
     * @return
     */
    private String getRandomCode(){
        //1000~9999
        //[1000 ~ 10000)
        return (int)(Math.random() * 9000 + 1000) + "";
    }
}
